import React, { useState, useEffect } from 'react';
import { Table, Badge, Button, SearchIcon, UsersIcon, type TableColumn } from "@repo/ui";
import { UserStatus, UserRole } from "@repo/api";
import type { User } from "@repo/api";
import { getRoleDisplayName, getRoleColor } from '../../utils/roleUtils';
import styles from './UserManagePage.module.css';

const UserManagePage: React.FC = () => {
  const [users, setUsers] = useState<User[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState<string>('all');
  const [roleFilter, setRoleFilter] = useState<string>('all');

  // 加载用户数据
  useEffect(() => {
    const loadUsers = async () => {
      try {
        setLoading(true);
        // TODO: 调用 API 获取用户数据
        // const response = await userService.getUsers();
        // setUsers(response.data);
        setUsers([]); // 暂时设为空数组
      } catch (error) {
        console.error('加载用户数据失败:', error);
      } finally {
        setLoading(false);
      }
    };

    loadUsers();
  }, []);

  const filteredUsers = users.filter(user => {
    const matchesSearch = user.username.toLowerCase().includes(searchTerm.toLowerCase()) ||
                         user.email.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === 'all' || user.status.toString() === statusFilter;
    const matchesRole = roleFilter === 'all' || user.role === roleFilter;
    return matchesSearch && matchesStatus && matchesRole;
  });

  const getStatusBadge = (status: UserStatus) => {
    const statusConfig = {
      [UserStatus.ACTIVE]: { text: '活跃', variant: 'success' as const },
      [UserStatus.INACTIVE]: { text: '非活跃', variant: 'warning' as const },
      [UserStatus.DISABLED]: { text: '已封禁', variant: 'error' as const }
    };
    
    const config = statusConfig[status];
    return <Badge variant={config.variant} size="sm">{config.text}</Badge>;
  };

  const getRoleBadge = (role: UserRole) => {
    const roleConfig = {
      [UserRole.ADMIN]: { text: getRoleDisplayName('admin'), variant: 'error' as const },
      [UserRole.MANAGER]: { text: getRoleDisplayName('manager'), variant: 'warning' as const },
      [UserRole.USER]: { text: getRoleDisplayName('user'), variant: 'default' as const },
      [UserRole.GUEST]: { text: getRoleDisplayName('guest'), variant: 'default' as const }
    };
    
    const config = roleConfig[role];
    return <Badge variant={config.variant} size="sm">{config.text}</Badge>;
  };

  const handleDeleteUser = (userId: number) => {
    if (window.confirm('确定要删除这个用户吗？')) {
      setUsers(users.filter(user => user.user_id !== userId));
    }
  };

  const handleToggleStatus = (userId: number) => {
    setUsers(users.map(user => {
      if (user.user_id === userId) {
        const newStatus = user.status === UserStatus.ACTIVE ? UserStatus.INACTIVE : UserStatus.ACTIVE;
        return { ...user, status: newStatus };
      }
      return user;
    }));
  };

  const columns: TableColumn[] = [
    { 
      key: 'user', 
      title: '用户信息', 
      dataIndex: 'username',
      render: (value: string, record: any) => (
        <div className={styles.userInfo}>
          <div className={styles.avatar}>
            {record.avatar ? (
              <img src={record.avatar} alt={value} />
            ) : (
              <div className={styles.avatarPlaceholder}>
                {value.charAt(0).toUpperCase()}
              </div>
            )}
          </div>
          <div className={styles.userDetails}>
            <div className={styles.username}>{value}</div>
            <div className={styles.email}>{record.email}</div>
          </div>
        </div>
      )
    },
    { 
      key: 'status', 
      title: '状态', 
      dataIndex: 'status',
      align: 'center',
      render: (value: UserStatus) => getStatusBadge(value)
    },
    { 
      key: 'role', 
      title: '角色', 
      dataIndex: 'role',
      align: 'center',
      render: (value: UserRole) => getRoleBadge(value)
    },
    { key: 'upload_count', title: '上传数量', dataIndex: 'upload_count', align: 'center' },
    { key: 'download_count', title: '下载数量', dataIndex: 'download_count', align: 'center' },
    { key: 'createdAt', title: '注册时间', dataIndex: 'created_at', align: 'center' },
    { key: 'lastLogin', title: '最后登录', dataIndex: 'last_login_at', align: 'center' },
    {
      key: 'actions',
      title: '操作',
      dataIndex: 'user_id',
      align: 'center',
      render: (value: number, record: any) => (
        <div className={styles.actions}>
          <Button
            size="sm"
            variant={record.status === UserStatus.ACTIVE ? 'destructive' : 'default'}
            onClick={() => handleToggleStatus(value)}
          >
            {record.status === UserStatus.ACTIVE ? '禁用' : '启用'}
          </Button>
          <Button
            size="sm"
            variant="destructive"
            onClick={() => handleDeleteUser(value)}
            disabled={record.role === UserRole.ADMIN}
          >
            删除
          </Button>
        </div>
      )
    }
  ];

  const statusCounts = {
    total: users.length,
    active: users.filter(u => u.status === UserStatus.ACTIVE).length,
    inactive: users.filter(u => u.status === UserStatus.INACTIVE).length,
    disabled: users.filter(u => u.status === UserStatus.DISABLED).length
  };

  const roleCounts = {
    admin: users.filter(u => u.role === UserRole.ADMIN).length,
    manager: users.filter(u => u.role === UserRole.MANAGER).length,
    user: users.filter(u => u.role === UserRole.USER).length,
    guest: users.filter(u => u.role === UserRole.GUEST).length
  };

  return (
    <div className={styles.container}>
      <div className={styles.header}>
        <div className={styles.headerContent}>
          <h1 className={styles.title}>用户管理</h1>
          <p className={styles.subtitle}>管理系统用户账户和权限</p>
        </div>
        
        <div className={styles.stats}>
          <div className={styles.statCard}>
            <div className={styles.statValue}>{statusCounts.total}</div>
            <div className={styles.statLabel}>总用户数</div>
          </div>
          <div className={styles.statCard}>
            <div className={`${styles.statValue} ${styles.statActive}`}>{statusCounts.active}</div>
            <div className={styles.statLabel}>活跃用户</div>
          </div>
          <div className={styles.statCard}>
            <div className={`${styles.statValue} ${styles.statInactive}`}>{statusCounts.inactive}</div>
            <div className={styles.statLabel}>非活跃用户</div>
          </div>
          <div className={styles.statCard}>
            <div className={`${styles.statValue} ${styles.statBanned}`}>{statusCounts.disabled}</div>
            <div className={styles.statLabel}>已禁用用户</div>
          </div>
        </div>
      </div>

      <div className={styles.roleStats}>
        <div className={styles.roleCard}>
          <div className={styles.roleIcon} style={{ backgroundColor: getRoleColor('admin') }}>
            <UsersIcon size={20} />
          </div>
          <div className={styles.roleContent}>
            <div className={styles.roleValue}>{roleCounts.admin}</div>
            <div className={styles.roleLabel}>{getRoleDisplayName('admin')}</div>
          </div>
        </div>
        
        <div className={styles.roleCard}>
          <div className={styles.roleIcon} style={{ backgroundColor: getRoleColor('manager') }}>
            <UsersIcon size={20} />
          </div>
          <div className={styles.roleContent}>
            <div className={styles.roleValue}>{roleCounts.manager}</div>
            <div className={styles.roleLabel}>{getRoleDisplayName('manager')}</div>
          </div>
        </div>
        
        <div className={styles.roleCard}>
          <div className={styles.roleIcon} style={{ backgroundColor: getRoleColor('user') }}>
            <UsersIcon size={20} />
          </div>
          <div className={styles.roleContent}>
            <div className={styles.roleValue}>{roleCounts.user}</div>
            <div className={styles.roleLabel}>{getRoleDisplayName('user')}</div>
          </div>
        </div>
        
        <div className={styles.roleCard}>
          <div className={styles.roleIcon} style={{ backgroundColor: getRoleColor('guest') }}>
            <UsersIcon size={20} />
          </div>
          <div className={styles.roleContent}>
            <div className={styles.roleValue}>{roleCounts.guest}</div>
            <div className={styles.roleLabel}>{getRoleDisplayName('guest')}</div>
          </div>
        </div>
      </div>

      <div className={styles.controls}>
        <div className={styles.searchBox}>
          <SearchIcon className={styles.searchIcon} size={20} />
          <input
            type="text"
            placeholder="搜索用户名或邮箱..."
            className={styles.searchInput}
            value={searchTerm}
            onChange={(e) => setSearchTerm(e.target.value)}
          />
        </div>
        
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>状态筛选:</label>
          <select 
            className={styles.filterSelect}
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value as any)}
          >
            <option value="all">全部</option>
            <option value={UserStatus.ACTIVE.toString()}>活跃</option>
            <option value={UserStatus.INACTIVE.toString()}>非活跃</option>
            <option value={UserStatus.DISABLED.toString()}>已禁用</option>
          </select>
        </div>
        
        <div className={styles.filterGroup}>
          <label className={styles.filterLabel}>角色筛选:</label>
          <select 
            className={styles.filterSelect}
            value={roleFilter}
            onChange={(e) => setRoleFilter(e.target.value as any)}
          >
            <option value="all">全部</option>
            <option value={UserRole.ADMIN}>{getRoleDisplayName('admin')}</option>
            <option value={UserRole.MANAGER}>{getRoleDisplayName('manager')}</option>
            <option value={UserRole.USER}>{getRoleDisplayName('user')}</option>
            <option value={UserRole.GUEST}>{getRoleDisplayName('guest')}</option>
          </select>
        </div>
      </div>

      <div className={styles.tableContainer}>
        <Table
          columns={columns}
          data={filteredUsers}
          loading={loading}
        />
      </div>
    </div>
  );
};

export default UserManagePage;
